<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
          autosize
          v-model="editUser.currentValue"
          :name="editUser.editKey"
          :label="editUser.editName"
          :placeholder="`请输入${editUser.editName}`"
          type="textarea"
      />
    </van-cell-group>

    <div style="margin: 30px 20px 0 20px;">
      <van-button round block color="#FC5833" native-type="submit">
        提交
      </van-button>
    </div>
    <div style="margin: 20px 20px 0 20px;">
      <van-button round block type="primary" @click="this.$router.back()">
        返回
      </van-button>
    </div>
  </van-form>

</template>

<script setup>
  import {useRoute} from "vue-router";
  import {ref} from "vue";
  import router from "@/router";
  import {updateUserInfo} from "@/api/user";
  import {Notify, Toast} from "vant";
  import {useStore} from "vuex";

  const route = useRoute();
  let store = useStore();

  const editUser = ref({
    editKey: route.query.editKey,
    currentValue: route.query.currentValue,
    editName: route.query.editName
  })

  const onSubmit = () => {
    if (editUser.value.editKey === 'avatar') {
      // avatar的url存在非法字符，所以这里先编码发送到后端，后端再解码
      editUser.value.currentValue = b64EncodeUnicode(editUser.value.currentValue);
    }
    // 提交信息到后台
    console.log(editUser.value.currentValue)
    updateUserInfo(editUser.value.editKey, editUser.value.currentValue).then(res => {
      if (res.code === 20000) {
        // 前端修改，可以减少一次后端获取用户信息的请求
        if (editUser.value.editKey === 'nickname') {
          store.state.user.nickname = editUser.value.currentValue;
        }
        if (editUser.value.editKey === 'avatar') {
          store.state.user.avatar = editUser.value.currentValue;
        }
        if (editUser.value.editKey === 'profile') {
          store.state.user.profile = editUser.value.currentValue;
        }
        if (editUser.value.editKey === 'phone') {
          store.state.user.phone = editUser.value.currentValue;
        }
        if (editUser.value.editKey === 'email') {
          store.state.user.email = editUser.value.currentValue;
        }
        Toast("修改成功");
        router.push('/my');
      } else {
        Notify({ type: 'warning', message: `${res.message}` });
      }
    }).catch(res => {
      console.log(res.message);
    });
  };

  const b64EncodeUnicode = (str) => {
    return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
      return String.fromCharCode('0x' + p1);
    }));
  }


</script>

<style scoped>

</style>
